#!/bin/bash
source print_jstat.sh
source tcpdump_file.sh

tmp_folder=$(date "+%Y%m%d%H%M%S")
mkdir ${tmp_folder}
touch ${tmp_folder}/iotop10_output.log
# io占用前十位
echo "记录IO占用前十位"
echo "iotop -o -b -n 1 | head -n 12 | awk '{print $1,$12}' > ${tmp_folder}/iotop10_output.log"
iotop -o -b -n 1 | head -n 12 | awk '{print $1,$12}' > ${tmp_folder}/iotop10_output.log

# CPU占用前十位
echo "记录CPU占用前十"
echo "ps -eo pid,comm,%cpu --sort=-%cpu | head -n 11 | tail -n +2 | awk '{print $2,$1}' > cpu_top_10.log"
touch ${tmp_folder}/cpu_top_10.log
ps -eo pid,comm,%cpu --sort=-%cpu | head -n 11 | tail -n +2 | awk '{print $2,$1}' > ${tmp_folder}/cpu_top_10.log

# 内存占用前十位
echo "记录内存占用前十位"
echo "ps -eo pid,comm,%mem --sort=-%mem | head -n 11 | tail -n +2 | awk '{print $2,$1}' > memory_top_10.log"
touch ${tmp_folder}/memory_top_10.log
ps -eo pid,comm,%mem --sort=-%mem | head -n 11 | tail -n +2 | awk '{print $2,$1}' > ${tmp_folder}/memory_top_10.log

# 打印线程信息
echo "开始获取线程信息"
echo "java进程列表如下:"
jps -l
read -p "请输入要查看的Java进程号：" process_id

read -p "请复现您的操作，脚本将开始抓包2分钟,已经准备好输入y回车:" sure_continue
if [ "${sure_continue}" = "y" ]; then

echo "正在记录线程信息"
nohup print_jstat ${tmp_folder} ${process_id} &
# 抓包
echo "正在记录TCP信息"
nohup tcp_dump_file ${tmp_folder} ${process_id} &
echo "程序正在进行抓包和获取进程信息，请等待两分钟."
echo "正在获取进程gc信息"
nohup sh jstat_gcutil_1000.sh ${tmp_folder} ${process_id} &
jstat_gcutil_1000_PID=$!
echo "正在保存内存快照"
nohup sh jmap_dump.sh ${tmp_folder} ${process_id} &
jmap_dump_PID=$!
echo "正在保存内存日志"
sh jmap_heap.sh ${tmp_folder} ${process_id}


sleep 120
kill -9 ${jstat_gcutil_1000_PID}

#等待jmap程序快照结束
while true; do
    # 使用ps命令检查进程是否存在
    if ps -p $jmap_dump_PID > /dev/null; then
        echo "正在保存内存快照，请稍等.."
    else
        echo "内存快照保存完毕."
        break  # 进程不存在时退出循环
    fi

    # 可选：等待一段时间后再次检查
    sleep 1
done

#获取程序日志
PROCESS_NAME=$(ps -p ${process_id} -o comm=)
foldername=${PROCESS_NAME}
mkdir -p ${tmp_folder}/log/${foldername}
current_date=$(date "+%m-%d")  # 当前日期的MM-dd格式
echo "正在拷贝日志"
find /log/${foldername} -type f -name "*${current_date}*" -exec cp {} ${tmp_folder}/log/${foldername} \;

else
  echo "\n"
fi



# 压缩程序文件夹
echo "开始压缩日志文件夹"
tar -zvcf ${tmp_folder}.tar.gz ${tmp_folder}/
rm -rf ${tmp_folder}
echo "压缩完成，请将:${tmp_folder}.tar.gz文件发给研发人员,谢谢"


